<template>
  <div class="role-list">
    <!-- 搜索栏 -->
    <div class="search-bar">
      <div class="search-label">角色名称</div>
      <el-input
        v-model="searchRoleName"
        placeholder="请输入角色名称"
        clearable
        class="search-input"
        @keyup.enter="searchRoles"
      />
      <el-button type="primary" @click="searchRoles" class="search-button">搜索</el-button>
      <el-button @click="resetSearch" class="search-button">重置</el-button>
    </div>

    <!-- 工具栏 -->
    <div class="button-group">
      <el-button type="primary" class="custom-button" @click="openAddDialog">新增</el-button>
      <el-button type="danger" class="custom-button" @click="deleteRoles">批量删除</el-button>
    </div>

    <!-- 角色表格 -->
    <el-table
      :data="paginatedRoles"
      border
      style="width: 100%"
      @selection-change="handleSelectionChange"
      row-key="id"
    >
      <el-table-column type="selection" width="50" align="center" />
      <el-table-column prop="index" label="序号" width="80" align="center" />
      <el-table-column prop="name" label="角色名称" align="center" width="200" />
      <el-table-column prop="desc" label="角色描述" align="center" />
      <el-table-column label="操作" width="450" align="center">
        <template #default="{ row }">
          <!-- <el-button
            type="primary"
            size="small"
            class="operation-button"
            @click="assignPermission(row)"
            >权限分配</el-button
          > -->
          <el-button type="primary" size="small" class="operation-button" @click="editRole(row)"
            >编辑</el-button
          >
          <el-button type="danger" size="small" class="operation-button" @click="deleteRole(row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="custom-pagination">
      <span>共 {{ roles.length }} 条</span>
      <select v-model="pageSize" @change="handleSizeChange" class="page-size-select">
        <option v-for="size in [10, 20, 30, 50]" :key="size" :value="size">{{ size }}条/页</option>
      </select>
      <button
        :disabled="currentPage === 1"
        @click="changePage(currentPage - 1)"
        class="pagination-button"
      >
        &lt;
      </button>
      <!-- 动态生成页码按钮 -->
      <button
        v-for="page in totalPages"
        :key="page"
        :class="['pagination-button', { 'current-page': page === currentPage }]"
        @click="changePage(page)"
      >
        {{ page }}
      </button>
      <button
        :disabled="currentPage === totalPages"
        @click="changePage(currentPage + 1)"
        class="pagination-button"
      >
        &gt;
      </button>
      <span>前往</span>
      <input
        type="number"
        v-model.number="jumpPage"
        @keyup.enter="jumpToPage"
        class="pagination-input"
        :max="totalPages"
        :min="1"
      />
      <span>页</span>
    </div>

    <!-- 新增角色弹窗 -->
    <el-dialog
      title="新增角色"
      v-model="addDialogVisible"
      width="600px"
      top="250px"
      @close="addDialogVisible = false"
    >
      <el-form :model="addForm" :rules="addFormRules" ref="addForm" label-width="80px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addForm.roleName" autocomplete="off" />
        </el-form-item>
        <el-form-item label="角色描述" prop="memo">
          <el-input v-model="addForm.memo" autocomplete="off" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="addDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleAddRole">确定</el-button>
      </template>
    </el-dialog>

    <!-- 编辑角色弹窗 -->
    <el-dialog
      title="编辑角色"
      v-model="editDialogVisible"
      width="600px"
      top="250px"
      @close="editDialogVisible = false"
    >
      <el-form :model="editForm" :rules="editFormRules" ref="editForm" label-width="80px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editForm.roleName" autocomplete="off" />
        </el-form-item>
        <el-form-item label="角色描述" prop="memo">
          <el-input v-model="editForm.memo" autocomplete="off" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleEditRole">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { getRoleList, saveRole, deleteRole, batchDeleteRoles, updateRole } from '@/api/role'

export default {
  data() {
    return {
      roles: [],
      selectedRoles: [],
      pageSize: 10,
      currentPage: 1,
      jumpPage: 1,
      searchRoleName: '', // 搜索角色名称
      filteredRoles: [],
      addDialogVisible: false,
      editDialogVisible: false,
      // 新增角色表单
      addForm: {
        roleName: '',
        memo: '',
      },
      // 新增角色表单验证规则
      addFormRules: {
        roleName: [{ required: true, message: '请输入角色名称', trigger: 'blur' }],
        memo: [{ required: true, message: '请输入角色描述', trigger: 'blur' }],
      },
      editForm: {
        roleId: '',
        roleName: '',
        memo: '',
      },
      editFormRules: {
        roleName: [{ required: true, message: '请输入角色名称', trigger: 'blur' }],
        memo: [{ required: true, message: '请输入角色描述', trigger: 'blur' }],
      },
    }
  },
  computed: {
    // 分页逻辑
    paginatedRoles() {
      const start = (this.currentPage - 1) * this.pageSize
      const end = start + this.pageSize
      return this.filteredRoles.slice(start, end).map((role, idx) => ({
        ...role,
        index: start + idx + 1,
      }))
    },
    // 计算总页数
    totalPages() {
      return Math.ceil(this.filteredRoles.length / this.pageSize)
    },
  },
  methods: {
    // 处理选择变化
    handleSelectionChange(selection) {
      this.selectedRoles = selection
    },
    // 处理每页条数变化
    handleSizeChange() {
      this.currentPage = 1
    },
    // 处理页码变化
    changePage(page) {
      if (page >= 1 && page <= this.totalPages) {
        this.currentPage = page
      }
    },
    // 跳转到指定页码
    jumpToPage() {
      if (this.jumpPage >= 1 && this.jumpPage <= this.totalPages) {
        this.currentPage = this.jumpPage
      } else {
        this.$message.warning('请输入有效的页码')
      }
    },
    // 打开新增角色弹窗
    openAddDialog() {
      this.addDialogVisible = true
      this.addForm = { roleName: '', memo: '' }
    },
    // 新增角色
    handleAddRole() {
      this.$refs.addForm.validate((valid) => {
        if (valid) {
          saveRole(this.addForm).then(() => {
            this.$message.success('新增角色成功')
            this.addDialogVisible = false
            // 刷新角色列表
            getRoleList().then((list) => {
              this.roles = list
              this.filteredRoles = list
            })
          })
        }
      })
    },
    // 批量删除角色
    deleteRoles() {
      if (this.selectedRoles.length === 0) {
        this.$message.warning('请至少选择一个角色')
        return
      }
      this.$confirm('确定要批量删除选中的角色吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          // 提取选中角色的id数组
          const ids = this.selectedRoles.map((item) => item.id)
          batchDeleteRoles(ids).then(() => {
            this.$message.success('批量删除成功')
            // 刷新角色列表
            getRoleList().then((list) => {
              this.roles = list
              this.filteredRoles = list
            })
          })
        })
        .catch(() => {
          // 用户取消
        })
    },
    // 权限分配
    assignPermission(role) {
      this.$message.info('权限分配功能（示例）')
    },
    // 编辑角色
    editRole(row) {
      this.editForm = {
        roleId: row.id,
        roleName: row.name,
        memo: row.desc,
      }
      this.editDialogVisible = true
    },
    // 修改角色
    handleEditRole() {
      this.$refs.editForm.validate((valid) => {
        if (valid) {
          updateRole(this.editForm).then(() => {
            this.$message.success('修改角色成功')
            this.editDialogVisible = false
            // 刷新角色列表
            getRoleList().then((list) => {
              this.roles = list
              this.filteredRoles = list
            })
          })
        }
      })
    },
    // 删除角色
    deleteRole(row) {
      this.$confirm('确定要删除该角色吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          deleteRole(row.id).then(() => {
            this.$message.success('删除成功')
            // 刷新角色列表
            getRoleList().then((list) => {
              this.roles = list
              this.filteredRoles = list
            })
          })
        })
        .catch(() => {
          // 用户取消
        })
    },
    // 搜索角色
    searchRoles() {
      this.currentPage = 1
      if (this.searchRoleName.trim() === '') {
        this.filteredRoles = this.roles
      } else {
        this.filteredRoles = this.roles.filter((role) =>
          role.name.includes(this.searchRoleName.trim()),
        )
      }
    },
    // 重置搜索
    resetSearch() {
      this.searchRoleName = ''
      this.filteredRoles = this.roles
      this.currentPage = 1
    },
  },
  mounted() {
    getRoleList().then((list) => {
      this.roles = list
      this.filteredRoles = list
    })
  },
}
</script>

<style scoped>
.role-list {
  padding: 20px;
  background-color: #f9f9f9;
}
/* 工具栏样式 */
.button-group {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
}

/* 表格调整 */
.el-table {
  margin-top: 0;
}

/* 按钮基础样式 */
.custom-button,
.operation-button {
  white-space: nowrap;
  padding: 5px 10px;
  border-radius: 4px;
  min-width: 100px;
}

/* 分页样式 */
.custom-pagination {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-top: 20px;
  font-size: 16px;
}

.page-size-select {
  border: 1px solid #dcdfe6;
  outline: none;
  box-shadow: none;
  background: #fff;
}

.pagination-button {
  padding: 2px 6px;
  border: 1px solid #ccc;
  border-radius: 4px;
  min-width: 30px;
}

.pagination-button.current-page {
  background-color: #409eff;
  color: #fff;
  border-color: #409eff;
}

.pagination-input {
  width: 40px;
  text-align: center;
  padding: 2px;
  outline: none;
  box-shadow: none;
  border: 1px solid #dcdfe6;
  background: #fff;
}

.search-bar {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 10px;
}
.search-input {
  width: 200px;
}
.search-button {
  min-width: 60px;
}
.search-label {
  white-space: nowrap; /* 禁止换行 */
  font-size: 14px;
}
</style>
